package com.blustreaksw.cyclecoach.main;

import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;

import com.blustreaksw.cyclecoach.MainActivity;
import com.blustreaksw.cyclecoach.MainActivity.UpdateActiveWorkoutScreenDataCallback;
import com.blustreaksw.cyclecoach.R;
import com.blustreaksw.cyclecoach.UserManagementActivity;
import com.blustreaksw.cyclecoach.UserProfileActivity;
import com.blustreaksw.cyclecoach.data.UserProfile;

public class Fragment_ActiveWorkout extends Fragment {
	
	TableRow mActiveWorkout_inProgressControlsRow;
	TableRow mActiveWorkout_startControlRow;
	Button mActiveWorkout_startButton;
	Button mActiveWorkout_stopLapButton;
	Button mActiveWorkout_pauseResumeButton;
	
	TextView mCadenceTextView;
	TextView mHeartRateTextView;
	TextView mPowerTextView;
	TextView mSpeedTextView;
	TextView mElapsedTimeTextView;
	TextView mDistanceTextView;
	
	private static final String TAG = "Fragment_ActiveWorkout";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_active_workout,
				container, false);
		v.setKeepScreenOn(true);
		setHasOptionsMenu(true);
		getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);
        getActivity().getActionBar().setHomeButtonEnabled(false);
        getActivity().getActionBar().setTitle("CycleCoach");
        getActivity().getActionBar().setSubtitle(null);
        
		mCadenceTextView = (TextView)v.findViewById(R.id.activeWorkout_cadenceTextView);
		mHeartRateTextView = (TextView)v.findViewById(R.id.activeWorkout_heartRateTextView);
		mPowerTextView = (TextView)v.findViewById(R.id.activeWorkout_powerTextView);
		mSpeedTextView = (TextView)v.findViewById(R.id.activeWorkout_speedTextView);
		mElapsedTimeTextView = (TextView)v.findViewById(R.id.activeWorkout_elapsedTimeTextView);
		mDistanceTextView = (TextView)v.findViewById(R.id.activeWorkout_distanceTraveledTextView);
		
		mActiveWorkout_stopLapButton = (Button)v.findViewById(R.id.activeWorkout_lapStopButton);
		mActiveWorkout_stopLapButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if(mActiveWorkout_stopLapButton.getText().equals(getString(R.string.activeWorkoutLabel_stopButton))) {
					getActivity().getSupportFragmentManager().popBackStack();
					((MainActivity)getActivity()).stopWorkoutSession();
				} else {
					// TODO
					// Handle lap increment
				}
			}
			
		});
		
		mActiveWorkout_inProgressControlsRow = (TableRow)v.findViewById(R.id.activeWorkout_controlButtonsRow);
		mActiveWorkout_startControlRow = (TableRow)v.findViewById(R.id.activeWorkout_startButtonRow);
		mActiveWorkout_startButton = (Button)v.findViewById(R.id.activeWorkout_startButton);
		mActiveWorkout_startButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Workout started so update status in MainActivity
				((MainActivity)getActivity()).startWorkoutSession();
				
				mActiveWorkout_startControlRow.setVisibility(View.GONE);
				mActiveWorkout_inProgressControlsRow.setVisibility(View.VISIBLE);
				mActiveWorkout_stopLapButton.setText(getString(R.string.activeWorkoutLabel_lapButton));
				mActiveWorkout_stopLapButton.setBackgroundColor(0xFF4C4C4C); // grey
				mActiveWorkout_pauseResumeButton.setText(getString(R.string.activeWorkoutLabel_pauseButton));
				mActiveWorkout_pauseResumeButton.setBackgroundColor(0xFFA30000); // red
			}
			
		});
		
		mActiveWorkout_pauseResumeButton = (Button)v.findViewById(R.id.activeWorkout_pauseResumeButton);
		mActiveWorkout_pauseResumeButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mActiveWorkout_pauseResumeButton.getText().equals(getString(R.string.activeWorkoutLabel_pauseButton))) {
					
					((MainActivity)getActivity()).pauseWorkoutSession();
					
					mActiveWorkout_pauseResumeButton.setBackgroundColor(0xFF004C00); // green
					mActiveWorkout_pauseResumeButton.setText(getString(R.string.activeWorkoutLabel_resumeButton));
					
					mActiveWorkout_stopLapButton.setBackgroundColor(0xFFA30000); // red
					mActiveWorkout_stopLapButton.setText(getString(R.string.activeWorkoutLabel_stopButton));
				} else {
					
					((MainActivity)getActivity()).resumeWorkoutSession();
					
					mActiveWorkout_stopLapButton.setText(getString(R.string.activeWorkoutLabel_lapButton));
					mActiveWorkout_stopLapButton.setBackgroundColor(0xFF4C4C4C); // grey
					mActiveWorkout_pauseResumeButton.setText(getString(R.string.activeWorkoutLabel_pauseButton));
					mActiveWorkout_pauseResumeButton.setBackgroundColor(0xFFA30000); // red
				}
			}
			
		});
		
		if(((MainActivity)getActivity()).isWorkoutActive()) {
			Log.d(TAG, "Workout is still active.");
			mActiveWorkout_startControlRow.setVisibility(View.GONE);
		} else {
			mActiveWorkout_inProgressControlsRow.setVisibility(View.GONE);
		}
		
		return v;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		((MainActivity)getActivity()).startClientNotifications(mUpdateScreenDataCallback);
		getActivity().invalidateOptionsMenu(); 
		
	}
	
	@Override
	public void onPause() {
		super.onPause();
		((MainActivity)getActivity()).stopClientNotifications();
	}
	
	/* Called whenever we call invalidateOptionsMenu() */
    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        menu.findItem(R.id.action_changeUser).setVisible(false);
        menu.findItem(R.id.action_history).setVisible(false);
        
        menu.findItem(R.id.scanning_indicator).setActionView(R.layout.progress_indicator).setVisible(false);
		menu.findItem(R.id.action_createUserWizard_restartDeviceScan).setVisible(false);
		menu.findItem(R.id.action_musicPlayerExternalLink).setVisible(true);
		menu.findItem(R.id.action_createUserWizard_cancelButton).setVisible(false);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action buttons
        switch(item.getItemId()) {
	        case R.id.action_musicPlayerExternalLink:
	            startActivity(Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
	            	    Intent.CATEGORY_APP_MUSIC));
	            return true;
	
	        default:
	            return super.onOptionsItemSelected(item);
        }
    }
	
	private UpdateActiveWorkoutScreenDataCallback mUpdateScreenDataCallback = new UpdateActiveWorkoutScreenDataCallback() {
		
		public void updateHrmField(final int hrm) {
			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					mHeartRateTextView.setText(Integer.toString(hrm));
				}
				
			});
			
		}
		public void updateCadenceField(final int cadence) {
			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					mCadenceTextView.setText(Integer.toString(cadence));
				}
				
			});
			
		}
		public void updatePowerField(final int power) {
			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					mPowerTextView.setText(Integer.toString(power));
				}
				
			});
			
		}
		public void updateSpeedField(final double speed) {
			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if(((UserProfileActivity)getActivity()).getUserProfile().getDisplayUnits().equals(UserProfile.MeasurementUnits.ENGLISH)) {
						mSpeedTextView.setText(String.format("%1.2f", speed * 0.621371));
					} else {
						mSpeedTextView.setText(String.format("%1.2f", speed));
					}
				}
				
			});
			
		}
		public void updateTimeField(final int time) {
			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					int hours = time / 3600;
					int minutes = (time % 3600) / 60;
					int seconds = time % 60;
					if(hours == 0) {
						mElapsedTimeTextView.setText(
								String.format("%d:%02d", minutes, seconds));
						Log.d(TAG, String.format("%d:%02d", minutes, seconds));
					} else {
						mElapsedTimeTextView.setText(
								String.format("time: %d:%02d:%02d", hours, minutes, seconds));
						Log.d(TAG, String.format("time: %d:%02d:%02d", hours, minutes, seconds));
					}
					
				}
				
			});
			
		}
		public void updateDistanceField(final double distance) {
			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if(((UserProfileActivity)getActivity()).getUserProfile().getDisplayUnits().equals(UserProfile.MeasurementUnits.ENGLISH)) {
						mDistanceTextView.setText(String.format("%1.2f", distance * 0.000621371));
						
					} else {
						mDistanceTextView.setText(String.format("%1.2f", distance / 1000));
					}
				}
				
			});
			
		}
	};
}
